//
//  CHSendNotification.m
//  ChildHoodStemp
//
//  Created by zhuxuehang on 13-12-3.
//
//

#import "MutiltimediaView.h"
#import "CHSendNotification.h"
#import "UIUtil.h"
#import "MicroDef.h"
#import "Snsp.pb.h"
#import "MutiltimediaView.h"
#import "ChatToolBar.h"
#import "ChatToolMoreView.h"
#import "EmotionView.h"
#import "TouchTable.h"
#import <QuartzCore/QuartzCore.h>
#import "CBEmotionView.h"
#import "ChildHoodMemory.h"
#import "ChildHoodService.h"
//#import "CHNoticeService.h"
#import "ChildHoodUser.h"
#import "QBImagePickerController.h"
//#import "CHNotifyViewTeacher.h"

#import "VoiceConverter.h"
#import "CHSAudioPlayer.h"
#import <AVFoundation/AVFoundation.h>
#import "CHSVoiceRecorder.h"

@interface CHSendNotification ()<ChatToolDelegate,ChatMoreViewDelegate,TouchTableViewDelegate,CHSendNotiDelegate,UITableViewDataSource,UITableViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIAlertViewDelegate, QBImagePickerControllerDelegate>
{
    NSMutableString *_nameStr;
    CHNoticeType _style;
    NSMutableArray *_memoryArray;
    NSMutableArray *_clazzArray;
    NSMutableArray *_memIDArr;
    NSMutableArray *_clazzIDArr;

    
    CHSVoiceRecorder   *_recorder;
    NSString        *_myAudioFilePath;
    NSString        *_myAudioFileName;
    NSString        *_tempFileName;
    
    NSString* _contentText;
    NSString* _imgName;
    NSString* _tempStrToSevice;
    
    BOOL _isFromImageShowed;
}

@property (nonatomic,retain) TouchTable* tableView;
@property (nonatomic,retain) ChatToolBar* chatToolBar;
@property (nonatomic,retain) EmotionView* emoView;
@property (nonatomic,retain) ChatToolMoreView* moreView;
@property (nonatomic,weak) id<CHSendNotiDelegate>delegate;
@property (nonatomic,retain) NSMutableArray *memoryArray;
@property (nonatomic,retain) NSMutableArray *clazzArray;


@property (copy, nonatomic) NSString *myAudioFilePath;
@property (copy, nonatomic) NSString *myAudioFileName;
@property (copy, nonatomic) NSString *tempFileName;

@property (copy,nonatomic) NSString*contentText;
@property (copy,nonatomic) NSString*imgName;
@property (copy,nonatomic) NSString*tempStrToSevice;
@property (nonatomic, strong) UIImage *selectImage;

@end

@implementation CHSendNotification
@synthesize tableView = _tableView;
@synthesize chatToolBar = _chatToolBar;
@synthesize emoView = _emoView;
@synthesize delegate = _delegate;
@synthesize myAudioFileName = _myAudioFileName;
@synthesize myAudioFilePath = _myAudioFilePath;
@synthesize tempFileName = _tempFileName;
@synthesize clazzArray = _clazzArray;
@synthesize contentText = _contentText;
@synthesize imgName = _imgName;
@synthesize tempStrToSevice = _tempStrToSevice;


-(void)dealloc
{
//    NSLog(@"CHSendNotification dealloc");

    _delegate = nil;
    _tableView.delegate =nil;
    _tableView.touchDelegate = nil;
    [[ChatToolMoreView defaultMoreView] setMoreViewDelegate:nil];
    [_chatToolBar setChattoolDelegate:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self];

}

-(id)initWithMemoryArray:(NSMutableArray *) memoryArray andClazzArray:(NSMutableArray*)clazzArray
{
    self = [super init];
    if (self) {
        _memoryArray = memoryArray;
        _clazzArray = clazzArray;
    }
    return self;
}



- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.view setBackgroundColor:CommonColor];
    
    _style = 909;
    
    _memIDArr = [[NSMutableArray alloc]initWithCapacity:4];
    _nameStr = [[NSMutableString alloc] initWithString:@""];
    for (ChildHoodMemory *memory in _memoryArray) {
        [_nameStr appendFormat:@"%@  ",memory.name];
        [_memIDArr addObject:[NSNumber numberWithInt:memory.memoryId]];
    }
    
    _clazzIDArr = [[NSMutableArray alloc]initWithCapacity:4];
    
    int count = 0;
    for (ContactsGroup *group in _clazzArray) {
        [_nameStr appendFormat:@"%@  ",group.CGName];
        [_clazzIDArr addObject:[NSNumber numberWithInt:group.clazzId]];
        count += group.CGCount;
    }
    
//    self.delegate = self;
    
    //初始化语音发送
    _recorder = [[CHSVoiceRecorder alloc] init];
//    self.myAudioFileName = [NSString stringWithFormat:@"audio_%d",[[ChildHoodService defaultService].childHoodMemory getMemoryId]];
//    self.myAudioFilePath = [[ChildHoodService defaultService].childHoodUser getResourcePath];
    
	// Do any additional setup after loading the view.
    [self.navigationItem setHidesBackButton:YES];
    [self.navigationItem setNewTitle:@"群发通知"];
//    [self.navigationItem setLeftItemWithTarget:self action:@selector(backToNoticeBase:) image:@"back_bar_button.png" selectedImageName:@"back_bar_button_tapped.png" text:nil disabled:nil];
//    [self.navigationItem setRightItemWithTarget:nil action:nil title:[NSString stringWithFormat:@"%d人",[_memoryArray count]+count] font:[UIFont systemFontOfSize:18]];
    
    
    
  
    
    CGSize size = self.view.frame.size;
    
    CGRect tableFrame = CGRectMake(0.0f, 0.0f, size.width, size.height-44);
	_tableView = [[TouchTable alloc] initWithFrame:tableFrame style:UITableViewStylePlain];
	_tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
	_tableView.dataSource = self;
	_tableView.delegate = self;
    _tableView.touchDelegate = self;
    _tableView.decelerationRate = 0.7;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = [UIColor clearColor];
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_6_1
    if (IsIOS7)
        [_tableView setSeparatorInset:UIEdgeInsetsZero];
#endif
	[self.view addSubview:_tableView];
    
    CGFloat width = _tableView.frame.size.width;
    CGSize strsize = [_nameStr sizeWithFont:[UIFont systemFontOfSize:14.f]
                       constrainedToSize:CGSizeMake(width-20, 100)
                           lineBreakMode:NSLineBreakByTruncatingTail];
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width, strsize.height+20)];
    headerView.backgroundColor = CommonColor;
    
    UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width-10, strsize.height+5)];
    contentView.backgroundColor = [UIColor colorWithRed:221.f/255.f green:208.f/255.f blue:171.f/255.f alpha:1.0];
    contentView.center = CGPointMake(headerView.frame.size.width/2, headerView.frame.size.height/2);
    contentView.layer.cornerRadius = 6.f;
    contentView.clipsToBounds = YES;
    
    UILabel *name = [[UILabel alloc] init];
    name.frame = CGRectMake(0, 0, width-20, strsize.height);
    name.center = CGPointMake(contentView.frame.size.width/2, contentView.frame.size.height/2);
    name.font = [UIFont systemFontOfSize:14.f];
    name.text = _nameStr;
    name.textColor = [UIColor whiteColor];
    name.numberOfLines = 0;
    name.lineBreakMode = NSLineBreakByTruncatingTail;
    name.backgroundColor = [UIColor clearColor];
    
    [contentView addSubview:name];
    [headerView addSubview:contentView];
    [_tableView setTableHeaderView:headerView];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    CGSize size = self.view.frame.size;
    
    if (!_chatToolBar) {
        _chatToolBar = [ChatToolBar defaultChatToolBar];
        [_chatToolBar setChattoolDelegate:self];
        [_chatToolBar setFrame:CGRectMake(0,size.height - 44 - (IsIOS7?0:0), size.width, 44)];
        [self.view addSubview:_chatToolBar];
        [self.view bringSubviewToFront:_chatToolBar];
    }
    
    if (!_emoView) {
        _emoView = [EmotionView defaultEmoView];
        [_emoView setFrame:CGRectMake(0, HARDWARE_SCREEN_HEIGHT - 64, size.width, 184)];
        [self.view addSubview:_emoView];
    }
    
    if (!_moreView) {
        _moreView = [ChatToolMoreView defaultMoreView];
        [_moreView setMoreViewDelegate:self];
        [_moreView setFrame:CGRectMake(_chatToolBar.frame.origin.x - 110, _chatToolBar.frame.origin.y -50, 110, 50)];
        [self.view addSubview:_moreView];
    }
    
    if (!_chatToolBar.isVoiceShow) {
        [_chatToolBar setOriginFrameOfTool];
    }else{
        [_chatToolBar setNewFrameOfTool];
        
    }
    if (!_isFromImageShowed) {
        [_chatToolBar resetToolPositionToInitial];
    }else{
        _isFromImageShowed = NO;
    }

    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(chatToolBarMoved:) name:ChatToolBarMoved object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sendChatMessage:) name:SendChatMessage object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onNoticeCompleteNoti:) name:NOTIFY_MSG_NOTICE object:nil];

    
#if __IPHONE_OS_VERSION_MAX_ALLOWED <= __IPHONE_6_1
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
#else
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
#endif
    
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
//    [self resetChatTool];
//    [self setEditing:NO animated:YES];
//    _chatToolBar.proToolHeight = _chatToolBar.contentText.frame.size.height;
//    _chatToolBar = [ChatToolBar defaultChatToolBar];[_chatToolBar.contentText setText:@""];
//    [_chatToolBar removeFromSuperview];
//    _emoView = [EmotionView defaultEmoView];
//    [_emoView removeFromSuperview];
//    ChatToolMoreView* moreView = [ChatToolMoreView defaultMoreView];
//    [moreView removeFromSuperview];
//    
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)sendNotify
{
//    [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFY_REFRESH_NOTICE_TEACHER object:nil];
}

//-(void)onNoticeCompleteNoti:(NSNotification*)noti
//{
//    
//    ChildHoodNotice* tmp = [noti.object isKindOfClass:[ChildHoodNotice class]]?(ChildHoodNotice*)noti.object:nil;
//    [UIUtil hideMBProgressViewForView:self.view];
//    
//    if(tmp == nil){
//        [self sendNotify];
//        if(_recorder)
//        {
//            [_recorder cancelled];
//        }
//        [self.navigationController popToRootViewControllerAnimated:YES];
//
//        return;
//    }
//    
//    if (tmp.noticeStatus == kNoticeSendFailed) {
//        [UIUtil addAlertViewTitle:@"发送失败" message:@"退出返回？再试重发？" delegate:self cancelButtonTitle:@"返回" otherBtnTitle:@"重试"];
//    }
//    else if (tmp.noticeStatus == kNoticeOK) {
//        [self sendNotify];
//        [self.navigationController popToRootViewControllerAnimated:YES];
//    }else if(tmp.noticeStatus  == kNoticeSending)
//    {
//    }else
//    {
//        [self.navigationController popToRootViewControllerAnimated:YES];
//    }
//}

#pragma mark- --警告框--
//-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
//    switch (buttonIndex) {
//        case 0:
////            NSLog(@"返回");
//            [self back:nil];
//            break;
//        case 1:
////            NSLog(@"重试");
//            if ([UIUtil isNetworkReachable]) {
//                switch (_style) {
//                    case CHNoticeTypeText:
//                        [_service addNormalNotice:self.tempStrToSevice to:_memIDArr andClazzes:_clazzIDArr];
//                        break;
//                    case CHNoticeTypePicture:
//                        [_service addFileNotice:self.tempStrToSevice type:SNSPMaterialTypeKImage to:_memIDArr andClazzes:_clazzIDArr];
//                        break;
//                    case CHNoticeTypeVoice:
//                        [_service addFileNotice:self.tempStrToSevice type:SNSPMaterialTypeKAudio to:_memIDArr andClazzes:_clazzIDArr];
//                        break;
//                    default:
//                        break;
//                }
//            }
//            break;
//        default:
//            break;
//    }
//    [UIUtil addMBProgressViewTitle:@"正在发送" inView:self.view alpha:0.5];
//}

#pragma mark- --Self Methods--
-(void)backToNoticeBase:(id)sender
{
    [UIUtil hideMBProgressViewForView:self.view];
//    NSLog(@"POP_NOTICE:%@",_noticeBase);
    [self.navigationController popToViewController:_noticeBase animated:YES];
}

- (void)scrollToBottomAnimated:(BOOL)animated
{
    NSInteger rows = [self.tableView numberOfRowsInSection:0];
    
    if(rows > 0) {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:rows - 1 inSection:0]
                              atScrollPosition:UITableViewScrollPositionBottom
                                      animated:animated];
    }
}

- (NSString *)stringFromDate:(NSDate *)date
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy_MM_dd_HH_mm_ss"];
    NSString *destDateString = [dateFormatter stringFromDate:date];
    return destDateString;
}

#pragma mark- --chat--
-(void)resetChatTool
{
    [UIView animateWithDuration:0.3 animations:^{
        [_chatToolBar reSetChatTool];
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.3 animations:^{
            CGRect fra = self.tableView.frame;
            fra.size.height = HARDWARE_SCREEN_HEIGHT-64-_chatToolBar.frame.size.height;
            [self.tableView setFrame:fra];
            [self scrollToBottomAnimated:YES];
        }];
    }];
}

-(void)chatToolBarMoved:(NSNotification*)noti
{
    CGFloat movedHeight = [noti.object floatValue];
    
    CGRect fra = self.tableView.frame;
    if (movedHeight>=0) {
        //上移时设置
        fra.size.height = HARDWARE_SCREEN_HEIGHT-64-_chatToolBar.frame.size.height-movedHeight ;
    }else
    {
        //返回时设置
        fra.size.height = HARDWARE_SCREEN_HEIGHT-64-_chatToolBar.frame.size.height;
    }
    [UIView animateWithDuration:0.3 animations:^{
        [self.tableView setFrame:fra];
        
    } completion:^(BOOL finished) {
//        [self scrollToBottomAnimated:YES];
    }];
}

-(void)sendChatMessage:(NSNotification*)noti
{
    NSString* log = (NSString*)noti.object;
    //NSLog(@"接受聊天工具栏的信息 %@",log);
    [self sendTextMessage:log];
}

-(void)tableView:(UITableView *)tableView touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    _chatToolBar.proToolHeight = _chatToolBar.contentText.frame.size.height;
    CGRect fra = _chatToolBar.frame;
    if (fra.origin.y == HARDWARE_SCREEN_HEIGHT-64-_chatToolBar.frame.size.height) {
        return;
    }
    [self resetChatTool];
    [_chatToolBar setNewFrameOfTool];
}

#pragma mark --ChatMoreViewDelegate--
-(void)selectPicFromAlbum
{
    ChatToolMoreView* moreview = [ChatToolMoreView defaultMoreView];
    CGRect fra = moreview.frame;
    fra.origin.x = -110;
    [UIView animateWithDuration:0.2 animations:^{
        [moreview setFrame:fra];
    } completion:^(BOOL finished) {
        ChatToolBar *chatBar = [ChatToolBar defaultChatToolBar];
        chatBar.isMoreViewShow = !chatBar.isMoreViewShow;
        [moreview setHidden:YES];
        
        /*UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        [imagePickerController setDelegate:self];
        [imagePickerController setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
        [self presentViewController:imagePickerController animated:YES completion:nil];*/
        
        QBImagePickerController *imagePickerController = [[QBImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsMultipleSelection = YES;
        imagePickerController.maximumNumberOfSelection = 1;
        imagePickerController.disablePopAnimation = YES;
        //  CHSNavigationController *navigationController = [[CHSNavigationController alloc] initWithRootViewController:imagePickerController];
        [self.navigationController pushViewController:imagePickerController animated:YES];//:navigationController animated:YES completion:NULL];
        
        
    }];
}

-(void)takePhotosWithCamera
{
    ChatToolMoreView* moreview = [ChatToolMoreView defaultMoreView];
    CGRect fra = moreview.frame;
    fra.origin.x = -110;
    [UIView animateWithDuration:0.2 animations:^{
        [moreview setFrame:fra];
    } completion:^(BOOL finished) {
        ChatToolBar *chatBar = [ChatToolBar defaultChatToolBar];
        chatBar.isMoreViewShow = !chatBar.isMoreViewShow;
        [moreview setHidden:YES];
        
        /*UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        [imagePickerController setDelegate:self];
        if ([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerSourceTypeCamera]) {
            [imagePickerController setEditing:YES];
            [imagePickerController setSourceType:UIImagePickerControllerSourceTypeCamera];
        }
        else
        {
            [imagePickerController setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
        }
        [self presentViewController:imagePickerController animated:YES completion:nil];*/
                
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            
            UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
            [imagePickerController setDelegate:self];
            
            [imagePickerController setEditing:YES];
            [imagePickerController setSourceType:UIImagePickerControllerSourceTypeCamera];
            [self presentViewController:imagePickerController animated:YES completion:nil];
            
        }else
        {
            QBImagePickerController *imagePickerController = [[QBImagePickerController alloc] init];
            imagePickerController.delegate = self;
            imagePickerController.allowsMultipleSelection = YES;
            imagePickerController.maximumNumberOfSelection = 1;
            imagePickerController.disablePopAnimation = YES;
            //  CHSNavigationController *navigationController = [[CHSNavigationController alloc] initWithRootViewController:imagePickerController];
            [self.navigationController pushViewController:imagePickerController animated:YES];//:navigationController animated:YES completion:NULL];
            //[imagePickerController setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
        }

        
    }];
}
#pragma mark- --chattoolbar--VoiceDelegate--

-(void)voicebtnDown:(id)sender
{
//    NSLog(@"btndown");
    NSString *filename = [NSString stringWithFormat:@"%@_%@",self.myAudioFileName,[self stringFromDate:[NSDate date]]];
    self.tempFileName = filename;
    NSString *path = [NSString stringWithFormat:@"%@%@.caf",self.myAudioFilePath,filename];
//    NSLog(@"path:%@",path);
    [_recorder startRecordWithPath:path];
}
- (void)voicebtnUpInside:(id)sender
{
//    NSLog(@"btnupinside");
    [_recorder stopRecordWithCompletionBlock:^(NSInteger fileLenth) {
        NSString *amrFilePath = [NSString stringWithFormat:@"%@%@.amr",self.myAudioFilePath,self.tempFileName];
        NSString *wavFilePath = [NSString stringWithFormat:@"%@%@.caf",self.myAudioFilePath,self.tempFileName];
        if ([[NSFileManager defaultManager] fileExistsAtPath:wavFilePath]) {
            NSData *data = [NSData dataWithContentsOfFile:wavFilePath];
            [[VoiceConverter wavToAmr:data] writeToFile:amrFilePath atomically:YES];
            [[NSFileManager defaultManager] removeItemAtPath:wavFilePath error:nil];
            if ([UIUtil isNetworkReachable]) {
                //服务器添加
//                if (_noticeBase && [_noticeBase respondsToSelector:@selector(addFileNotice:type:to:andClazzes:withCheckCode:)]) {
//                    [_noticeBase addFileNotice:[NSString stringWithFormat:@"%@.amr",self.tempFileName]  type:SNSPMaterialTypeKAudio to:_memIDArr andClazzes:_clazzIDArr withCheckCode:nil];
//                }
//                self.tempStrToSevice = [NSString stringWithFormat:@"%@.amr",self.tempFileName];
//                _style = CHNoticeTypeVoice;
//                //界面添加
//                [self sendContentInCell:nil imgName:nil type:CHNoticeTypeVoice];
            }
            [self sendNotify];
            [UIUtil addMBProgressViewTitle:@"正在发送" inView:self.view alpha:0.2 failureTitle:@"当前网络不可用，请检查网络"];
            [self performSelector:@selector(backToNoticeBase:) withObject:nil afterDelay:0.1];
        }
    }];
}
- (void)voicebtnUpOutside:(id)sender
{
//    NSLog(@"btnupoutside");
    [_recorder finishCancelled];
}
- (void)voicebtnDragExit:(id)sender
{
//    NSLog(@"btndragexit");
    [_recorder cancelled];
}
- (void)voicebtnDragEnter:(id)sender
{
//    NSLog(@"btndragenter");
    [_recorder recording];
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    _isFromImageShowed = YES;
    [picker dismissViewControllerAnimated:NO completion:nil];
    UIImage *aImg = [info objectForKey:UIImagePickerControllerOriginalImage];
    [self sendImageMessage:aImg];
    ChatToolBar *chatBar = [ChatToolBar defaultChatToolBar];
    [chatBar reSetChatTool];
    if (!chatBar.isVoiceShow) {
        [chatBar setOriginFrameOfTool];
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    _isFromImageShowed = YES;
    [picker dismissViewControllerAnimated:NO completion:nil];
    ChatToolBar *chatBar = [ChatToolBar defaultChatToolBar];
    [chatBar reSetChatTool];
    if (!chatBar.isVoiceShow) {
        [chatBar setOriginFrameOfTool];
    }
}
- (void)imagePickerController:(QBImagePickerController *)imagePickerController didFinishPickingMediaWithInfos:(id)info
{
    _isFromImageShowed = YES;

    /*   if (self.isHeaderImgNotImgMemoty) {
     UIImage *img = [info objectForKey:UIImagePickerControllerEditedImage];
     [_headerImageView setImage:img];
     }else
     */
    {
        if (imagePickerController.allowsMultipleSelection) {
            NSArray *mediaInfoArray = (NSArray *)info;
            //把数组中的元素传递给publishChildhoodView中
            //   PublishChildhoodView *publishChildView = [[PublishChildhoodView alloc] initWithViewStyle:PublishChildhoodViewTypePhoto];
            int count = mediaInfoArray.count;
            for (int i = 0; i < count; i++) {
                NSMutableDictionary *aDic = [mediaInfoArray objectAtIndex:i];
                UIImage *aImg = [aDic objectForKey:@"UIImagePickerControllerOriginalImage"];
                [self sendImageMessage:aImg];
                //  [publishChildView addPictureWithImage:aImg];
            }
            //   [self.navigationController pushViewController:publishChildView animated:YES];
        } else {
            // NSDictionary *mediaInfo = (NSDictionary *)info;
            //            NSLog(@"Selected: %@", mediaInfo);
        }
    }
    
    /*[picker dismissViewControllerAnimated:YES completion:nil];
     UIImage *aImg = [info objectForKey:UIImagePickerControllerOriginalImage];
     if (_delegate && [_delegate respondsToSelector:@selector(sendImageMessage:)]) {
     
     }
     ChatToolBar *chatBar = [ChatToolBar defaultChatToolBar];
     [chatBar reSetChatTool];
     if (!chatBar.isVoiceShow) {
     [chatBar setOriginFrameOfTool];
     }
     
     */
    //[imagePickerController.navigationController popViewControllerAnimated:YES];
    //[self dismissViewControllerAnimated:YES completion:NULL];
}

- (void)imagePickerControllerDidCancels:(QBImagePickerController *)imagePickerController
{
    _isFromImageShowed = YES;
    //    NSLog(@"Cancelled");
    [self dismissViewControllerAnimated:NO completion:NULL];
}





#pragma mark- --self Delegate--

-(void)sendImageMessage:(UIImage *)image
{
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        NSString* imgPath = [[ChildHoodService defaultService].childHoodUser getResourcePath];
//        //压缩图片大小尺寸
//        UIImage *aImg = [UIUtil scaleFromImage:image scaledToWidth:512];
//        NSData *imgData = UIImageJPEGRepresentation(aImg, 0.4);
//        NSLog(@"图片大小:%uKB",[imgData length]/1024);
//        //本地保存图片文件
//        NSString *fileName = [self addPictureToLocationPath:imgPath image:imgData];
//        if (_noticeBase && [_noticeBase respondsToSelector:@selector(addFileNotice:type:to:andClazzes:withCheckCode:)]) {
//            [_noticeBase addFileNotice:fileName type:SNSPMaterialTypeKImage to:_memIDArr andClazzes:_clazzIDArr withCheckCode:nil];
//        }
////        self.selectImage = [self decodedImageWithImage:image];
//
//        [self sendNotify];
//        dispatch_async(dispatch_get_main_queue(), ^{
//            if ([UIUtil isNetworkReachable]) {
//                //发送消息到服务器
////                NSLog(@"给%d个人发送图片",[_memIDArr count]);
////                self.tempStrToSevice = fileName;
////                _style = CHNoticeTypePicture;
//                //添加到界面
////                [self sendContentInCell:nil imgName:fileName type:CHNoticeTypePicture];
//            }
////            [self sendNotify];
//            [UIUtil addMBProgressViewTitle:@"正在发送" inView:self.view alpha:0.2];
//            [self performSelector:@selector(backToNoticeBase:) withObject:nil afterDelay:0.1];
//
//        });
//    });
//    [_chatToolBar reSetChatTool];

//    [self resetChatTool];
}
-(void)sendTextMessage:(NSString *)message
{
    if (![UIUtil isNetworkReachable]) {
        [UIUtil addMBProgressViewTitle:@"网络异常，请检查网络" inView:self.view alpha:0.5 hideDelayTime:1 failureTitle:@"当前网络不可用，请检查网络"];
        return;
    }
    //如果消息为空，则不发送,提示用户
    [[ChatToolBar defaultChatToolBar].contentText resignFirstResponder];
    [[ChatToolBar defaultChatToolBar] reSetChatTool];
//    if (![UIUtil isCanSendWithMessage:message]) {
//        [UIUtil addMBProgressViewTitle:@"内容不能为空" inView:self.view alpha:0.5 hideDelayTime:1];
//        return;
//    }
//    
//    if ([UIUtil isNetworkReachable]) {
//        if (_noticeBase && [_noticeBase respondsToSelector:@selector(addNormalNotice:to:andClazzes:withCheckCode:)]) {
//            [_noticeBase addNormalNotice:message to:_memIDArr andClazzes:_clazzIDArr withCheckCode:nil];
//        }
//
//        //添加到界面
////        [self sendContentInCell:message imgName:nil type:CHNoticeTypeText];
////        self.tempStrToSevice = message;
////        _style = CHNoticeTypeText;
//    }
//    [self sendNotify];
    [UIUtil addMBProgressViewTitle:@"正在发送" inView:self.view alpha:0.2 failureTitle:@"当前网络不可用，请检查网络"];
    [self performSelector:@selector(backToNoticeBase:) withObject:nil afterDelay:0.1];
}

-(NSString *)addPictureToLocationPath:(NSString*)aPath image:(NSData*)imgData
{
    //图片命名格式：img+roomID+memoryID+角色类型+时间.jpg,时间格式为年月日时分秒
    NSFileManager* imgManager = [NSFileManager defaultManager];
//    NSString* imgName = [NSString stringWithFormat:@"img%lld%d%@%@.jpg",_messageRoomID,[[ChildHoodService defaultService].childHoodMemory getMemoryId],[ChildHoodService defaultService].childHoodUser.relativeType,[UIUtil getCurrentTimeWithFormatYMDHMS]];
//    NSString* imgName = [NSString stringWithFormat:@"img%d%@%@.jpg",[[ChildHoodService defaultService].childHoodMemory getMemoryId],[ChildHoodService defaultService].childHoodUser.relativeType,[UIUtil getCurrentTimeWithFormatYMDHMS]];
//     [UIUtil createFilePath:aPath];
//    [imgManager createFileAtPath:[aPath stringByAppendingString:imgName] contents:imgData attributes:nil];
//    NSLog(@"图片保存路径：%@%@",aPath,imgName);
//    return imgName;
    return nil;
}

//当内容为语音时，只记录类型，不传递数据；当为文本和图片时，需要显示
-(void)sendContentInCell:(NSString*)contentText imgName:(NSString*)imgName type:(CHNoticeType)type
{
    _style = type;
    switch (type) {
        case CHNoticeTypeText:
        {
            self.contentText = contentText;
//            NSLog(@"%@",_contentText);
        }
            break;
        case CHNoticeTypePicture:
        {
//            NSString* imgPath = [[ChildHoodService defaultService].childHoodUser getResourcePath];
//            self.imgName = [NSString stringWithFormat:@"%@%@",imgPath,imgName];
//            NSLog(@"最终的_imgName：%@",_imgName);
        }
            break;
        case CHNoticeTypeVoice:
            break;
        default:
            break;
    }
    [self.tableView reloadData];
}

#pragma mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString* cellID = [NSString stringWithFormat:@"CELL_%d",_style];
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        cell.backgroundView = nil;
        cell.backgroundColor = ClearColor;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.accessoryView = nil;
        
        cell.imageView.image = nil;
        cell.imageView.hidden = YES;
        cell.textLabel.text = nil;
        cell.textLabel.hidden = YES;
        cell.detailTextLabel.text = nil;
        cell.detailTextLabel.hidden = YES;
        MutiltimediaView *_portraitView = [[MutiltimediaView alloc] initWithFrame:CGRectMake(HARDWARE_SCREEN_WIDTH-80, 20, 52, 52)] ;
        [_portraitView setBackgroundColor:ClearColor];
        [_portraitView setClipsToBounds:YES];
        [_portraitView.layer setCornerRadius:10];
        //    [_portraitView setTag:10001];
        [cell addSubview:_portraitView];
//        NSString *headerPath = [[ChildHoodService defaultService].childHoodMemory getProfilePictureUri];
//        [_portraitView setMultimediaFileUri:headerPath type:SNSPMaterialTypeKImage];
        
        UILabel *senderNameTitle = [[UILabel alloc] initWithFrame:CGRectMake(_portraitView.frame.origin.x, _portraitView.frame.origin.y +_portraitView.frame.size.height+4, 100,20)];
        
        //    self.senderNameTitle.text = @"11111";
        [senderNameTitle setTextColor: [UIUtil colorWithHexString:@"#595757" withAlpha:1]];
        [senderNameTitle setFont:Font16];
        [senderNameTitle setTextAlignment:NSTextAlignmentLeft];
        [senderNameTitle setBackgroundColor:ClearColor];
        [senderNameTitle setTag:10002];
        [cell addSubview:senderNameTitle];
//        [senderNameTitle setText:[ChildHoodService defaultService].childHoodMemory.name];
        
        if(_style >= CHNoticeTypeText && _style <= CHNoticeTypeVoice)
        {
            [senderNameTitle setHidden:NO];
            [_portraitView setHidden:NO];
        }
        else
        {
            [senderNameTitle setHidden:YES];
            [_portraitView setHidden:YES];
        }
        
        switch (_style)
        {
            case CHNoticeTypeText:
            {
                
                CGSize textsize = [CBEmotionView getTextHeightWithEmotionString:_contentText
                                                                       maxWidth:tableView.frame.size.width-30];
                
                UIImageView *textBgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, textsize.width+10, textsize.height+10)];
                
                textBgView.center = CGPointMake(cell.frame.size.width/2, (textsize.height+50)/2);
                
                textBgView.image = [[UIImage imageNamed:@"notic_create_background"] resizableImageWithCapInsets:UIEdgeInsetsMake(15, 40, 15, 40) resizingMode:UIImageResizingModeStretch];//[[[UIImage imageNamed:@"notic_create_background"] resizableImageWithCapInsets:UIEdgeInsetsMake(15, 40, 15, 40) resizingMode:UIImageResizingModeStretch] ] ];
                //                 [[textBgView setImage:[UIImage imageNamed:@"notic_create_background"] resizableImageWithCapInsets:UIEdgeInsetsMake(15, 40, 15, 40) resizingMode:UIImageResizingModeStretch] ]];
                
                
                //textBgView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"notic_create_background"]];//[UIColor colorWithRed:55.0/255 green:176.0/255 blue:195.0/255 alpha:1];
                textBgView.layer.cornerRadius = 10.0f;
                textBgView.clipsToBounds = YES;
                CBEmotionView *textLabel = [[CBEmotionView alloc] initWithFrame:CGRectMake(0, 0, textsize.width, textsize.height)
                                                                  emotionString:_contentText
                                                                      textColor:[UIUtil colorWithHexString:@"#595757" withAlpha:1]];
                textLabel.backgroundColor = [UIColor clearColor];
                textLabel.center = CGPointMake(textBgView.frame.size.width/2, textBgView.frame.size.height/2);
                [textBgView addSubview:textLabel];
                [cell.contentView addSubview:textBgView];
                break;
            }
            case CHNoticeTypePicture:
            {
                CGSize imgSize = CGSizeMake(80, 80);
                
                
                UIImageView *bgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, imgSize.width*1.05, imgSize.height*1.05)];
                bgView.center = CGPointMake(cell.frame.size.width/2, 75);
                
                
                bgView.image =  [[UIImage imageNamed:@"notic_create_background"] resizableImageWithCapInsets:UIEdgeInsetsMake(15, 40, 15, 40) resizingMode:UIImageResizingModeStretch];
                
                bgView.layer.cornerRadius = 10.0f;
                bgView.clipsToBounds = YES;
                
                UIImageView *picture = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, imgSize.width, imgSize.height)];
                picture.center = CGPointMake(bgView.frame.size.width/2, bgView.frame.size.height/2);
                picture.backgroundColor = [UIColor grayColor];
                picture.layer.cornerRadius = 12.0f;
                
                picture.contentMode =  UIViewContentModeScaleAspectFill;
                picture.clipsToBounds = YES;
                
//                UIImage* img = [UIImage imageWithContentsOfFile:_imgName];
                [picture setImage:_selectImage];
                
                [bgView addSubview:picture];
                [cell.contentView addSubview:bgView];
                break;
            }
            case CHNoticeTypeVoice:
            {
                
                UIImageView *bgView = [[UIImageView alloc] initWithFrame:CGRectMake(HARDWARE_SCREEN_WIDTH-90-80, 20, 80, 47)];
                //  bgView.center = CGPointMake(cell.frame.size.width/2, 75);
                
                [cell.contentView addSubview:bgView];
//                MutiltimediaView *voiceView = [[MutiltimediaView alloc] initWithFrame:CGRectMake(30, 20, 150, 60)];
                MutiltimediaView *voiceView = [[MutiltimediaView alloc] initWithFrame:CGRectMake(HARDWARE_SCREEN_WIDTH-90-80, 20, 80, 47)];
                
                
                [bgView setImage:[[UIImage imageNamed:@"bubble-default-sended.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 40, 0, 40) resizingMode:UIImageResizingModeStretch]];
                
                [bgView addSubview:voiceView];
                
                
                [voiceView setBackgroundColor:[UIColor clearColor]];
                voiceView.tag = 2348432;
                voiceView.layer.cornerRadius = 10.0f;
                voiceView.clipsToBounds = YES;
//                UIImage *voiceImg = [UIImage imageNamed:@"audio_notice_play_left_animate_03.png"];
                UIImage *voiceImg = [UIImage imageNamed:@"audio_play_right_animate_03.png"];
                UIImageView *voice = [[UIImageView alloc] initWithImage:voiceImg];
                voice.frame = CGRectMake(40, (47-30)/2, 24, 30);
//                voice.center = CGPointMake(50, 30);
                [voiceView addSubview:voice];
                UILabel *time1 = [[UILabel alloc] initWithFrame:CGRectMake(voiceView.frame.origin.x-30,
                                                                          voiceView.frame.origin.y+voiceView.frame.size.height-20, 30, 20)];
                time1.font = Font14;
                time1.textColor = ContentDarkGrayColor;
                time1.backgroundColor = [UIColor clearColor];
                time1.textAlignment = NSTextAlignmentLeft;
                //time.text = @"10\"";
                time1.text = [NSString stringWithFormat:@"%d\"",(int)_recorder.recordTime];
                [cell.contentView addSubview:voiceView];
                [cell.contentView addSubview:time1];
                break;
            }
            default:
                break;
        }
    }
    return cell;
}

#pragma mark UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = 0;
    switch (_style)
    {
        case CHNoticeTypeText:
        {
            CGSize textsize = [CBEmotionView getTextHeightWithEmotionString:_contentText
                                                                   maxWidth:tableView.frame.size.width-30];
            height = textsize.height+50;
            break;
        }
        case CHNoticeTypePicture:
        {
            height = 150;
            break;
        }
        case CHNoticeTypeVoice:
        {
            height = 100;
            break;
        }
        default:
            break;
    }
    return height;
}

//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
//{
//    
//    CGSize size = [_nameStr sizeWithFont:[UIFont systemFontOfSize:14.f]
//                       constrainedToSize:CGSizeMake(tableView.frame.size.width-20, 100)
//                           lineBreakMode:NSLineBreakByTruncatingTail];
//    return size.height+10;
//}

//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
//{
//    if (section==0) {
//        CGFloat width = tableView.frame.size.width;
//        CGSize size = [_nameStr sizeWithFont:[UIFont systemFontOfSize:14.f]
//                           constrainedToSize:CGSizeMake(width-20, 100)
//                               lineBreakMode:NSLineBreakByTruncatingTail];
//        UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, width, size.height+10)] autorelease];
//        headerView.backgroundColor = CommonColor;
//        
//        UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width-10, size.height+5)];
//        contentView.backgroundColor = [UIColor colorWithRed:221.f/255.f green:208.f/255.f blue:171.f/255.f alpha:1.0];
//        contentView.center = CGPointMake(headerView.frame.size.width/2, headerView.frame.size.height/2);
//        contentView.layer.cornerRadius = 6.f;
//        contentView.clipsToBounds = YES;
//        
//        UILabel *name = [[UILabel alloc] init]; 
//        name.frame = CGRectMake(0, 0, width-20, size.height);
//        name.center = CGPointMake(contentView.frame.size.width/2, contentView.frame.size.height/2);
//        name.font = [UIFont systemFontOfSize:14.f];
//        name.text = _nameStr;
//        name.textColor = [UIColor whiteColor];
//        name.numberOfLines = 0;
//        name.lineBreakMode = NSLineBreakByTruncatingTail;
//        name.backgroundColor = [UIColor clearColor];
//        
//        [contentView addSubview:name];
//        [headerView addSubview:contentView];
//        [name release];
//        [contentView release];
//        return headerView;
//    }
//    return nil;
//}


#pragma mark - 解压图片
- (UIImage *)decodedImageWithImage:(UIImage *)image {
    if (image.images) {
        // Do not decode animated images
        return image;
    }
    
    CGImageRef imageRef = image.CGImage;
    CGSize imageSize = CGSizeMake(CGImageGetWidth(imageRef), CGImageGetHeight(imageRef));
    CGRect imageRect = (CGRect){.origin = CGPointZero, .size = imageSize};
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef);
    
    int infoMask = (bitmapInfo & kCGBitmapAlphaInfoMask);
    BOOL anyNonAlpha = (infoMask == kCGImageAlphaNone ||
                        infoMask == kCGImageAlphaNoneSkipFirst ||
                        infoMask == kCGImageAlphaNoneSkipLast);
    
    // CGBitmapContextCreate doesn't support kCGImageAlphaNone with RGB.
    // https://developer.apple.com/library/mac/#qa/qa1037/_index.html
    if (infoMask == kCGImageAlphaNone && CGColorSpaceGetNumberOfComponents(colorSpace) > 1) {
        // Unset the old alpha info.
        bitmapInfo &= ~kCGBitmapAlphaInfoMask;
        
        // Set noneSkipFirst.
        bitmapInfo |= kCGImageAlphaNoneSkipFirst;
    }
    // Some PNGs tell us they have alpha but only 3 components. Odd.
    else if (!anyNonAlpha && CGColorSpaceGetNumberOfComponents(colorSpace) == 3) {
        // Unset the old alpha info.
        bitmapInfo &= ~kCGBitmapAlphaInfoMask;
        bitmapInfo |= kCGImageAlphaPremultipliedFirst;
    }
    
    // It calculates the bytes-per-row based on the bitsPerComponent and width arguments.
    CGContextRef context = CGBitmapContextCreate(NULL,
                                                 imageSize.width,
                                                 imageSize.height,
                                                 CGImageGetBitsPerComponent(imageRef),
                                                 0,
                                                 colorSpace,
                                                 bitmapInfo);
    CGColorSpaceRelease(colorSpace);
    
    // If failed, return undecompressed image
    if (!context) return image;
    
    CGContextDrawImage(context, imageRect, imageRef);
    CGImageRef decompressedImageRef = CGBitmapContextCreateImage(context);
    
    CGContextRelease(context);
    
    UIImage *decompressedImage = [UIImage imageWithCGImage:decompressedImageRef scale:image.scale orientation:image.imageOrientation];
    CGImageRelease(decompressedImageRef);
    return decompressedImage;
}

@end
